# Filters added to this controller will be run for all controllers in the application.
# Likewise, all the methods added will be available for all controllers.
class ApplicationController < ActionController::Base
  include Sitealizer
  helper :application
  before_filter :set_charset,:active_user,:use_sitealizer
  session_times_out_in 600, :before_timeout=> :reset_user
  
  def timeout_authorize
    flash[:notice]=["登陆超时，请重新登陆"]
    redirect_to :controller => "login", :action=>"login"
  end
  
  def set_charset
    headers["Content-Type"] = "text/html; charset=UTF-8"
  end
  
  #active user
  def active_user
    control_name=params[:control]||"index"
    action_name=params[:action]||"index"
    obj_id=params[:id]||"0"
    @activeuser=ActiveUser.active_user(session[:active_user_id],request.env["REMOTE_HOST"],cookies[:auth_token])
    @activeuser.log_action(control_name,action_name,obj_id.to_i)
    session[:active_user_id]=@activeuser.id
  end
  
  #clear activeuser session
  def remove_session
    reset_user
    reset_session
  end
  
  def reset_user
    ActiveUser.remove_active_user(session[:active_user_id])
    cookies.delete :auth_token
  end
  
  private 
  def error_messages_of(object)
    ret=[]
    object.errors.each  { |error| text<<['<li>'+error[1].to_s+'</li>']} if object && !object.errors.empty?
    return ret=[]
  end
  
  def user_authorize
    if @activeuser.guest?
      flash[:notice]=["请用注册用户重新登陆"]
      if request.xhr?
        render :update do |page|
          page.redirect_to :controller => "login", :action=>"login"
        end
      else
        redirect_to :controller => "login", :action=>"login"
      end
    end
  end
  
  def admin_authorize
    unless @activeuser.adminstrative?
      remove_session
      flash[:notice]=["请以管理员账号重新登陆"]
      if request.xhr?
        render :update do |page|
          page.redirect_to :controller => "login", :action=>"login"
        end
      else
        redirect_to :controller => "login", :action=>"login"
      end
    end
  end
  
end